import React, { Component, createRef } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Space, message } from "antd";
import Captcha from "../../components/Captcha";
import { withRouter } from "react-router-dom";
// 引入封装后的axios
import axios from "@/http/http";
// 引入请求地址对象
import url from "@/config/url";
class MobileLogin extends Component {
  state = {
    key: "", // 验证码子组件传给当前组件的key,是验证码的唯一标识
    time: 30, // 初始化的倒计时起始数字
    // timer:null
    disabledClick: true, // 设置登录按钮时禁用的
    requestId: "", // 短信发送成功后返回的requestId id
  };
  ref1 = createRef(); // 创建一个ref 引用对象, 给表单form 赋值
  ref2 = createRef(); //  创建一个ref 引用对象, 给图形验证码组件赋值
  // 该事件时子传父
  getKey = (key) => {
    // console.log(key); // 验证码标识符
    this.setState({
      key: key,
    });
  };
  render() {
    return (
      <div>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={this.onFinish}
          ref={this.ref1}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: "请输入手机号!",
                pattern: /^1[3-9]\d{9}$/, // 手机号的正则
              },
            ]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="手机号"
              size="large"
            />
          </Form.Item>
          <Space>
            <Form.Item
              name="captcha"
              rules={[{ required: true, message: "请输入验证码!" }]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="text"
                placeholder="验证码"
                size="large"
              />
            </Form.Item>
            <Form.Item>
              {/* 验证码组件 */}
              <Captcha getKey={this.getKey} w={120} ref={this.ref2}></Captcha>
            </Form.Item>
          </Space>

          {/* 短信验证码和发送短信验证码按钮 */}
          <Space>
            <Form.Item
              name="code"
              rules={[{ required: true, message: "请输入短信验证码!" }]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="短信验证码"
                size="large"
              />
            </Form.Item>
            <Form.Item>
              <Button
                size="large"
                disabled={this.state.time != 30}
                onClick={this.sendMsg}
              >
                {this.state.time != 30 ? this.state.time + "秒" : "发送短信"}
              </Button>
            </Form.Item>
          </Space>

          <Form.Item>
            <Button
              type="primary"
              disabled={this.state.disabledClick}
              size="large"
              block
              htmlType="submit"
              className="login-form-button"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }

  // 点击登录
  onFinish = (values) => {
    // values 为参数对象
    console.log(values);
    values.requestId = this.state.requestId;
    axios.post(url.msglogin, values).then((res) => {
      if (res.data.errNo === 0) {
        // 登录成功
        message.success("登录成功", 1);
        // 跳转首页
        this.props.history.push("/dashboard");
      } else {
        // 登录失败
        message.error(res.data.errText, 1);
        // 刷新图形验证码
        this.ref2.current.loadImg();
        this.ref1.current.setFieldsValue({
          mobile: "",
          captcha: "",
          code: "",
        });
      }
    });
  };
  // 定义倒计时变量
  timer = null;
  // 定义倒计时函数
  timeover = () => {
    this.timer = setInterval(() => {
      if (this.state.time == 0) {
        // 清除定时器
        clearInterval(this.timer);
        // 重新回归倒计时起始值30
        this.setState({
          time: 30,
        });
      } else {
        this.setState({
          time: this.state.time - 1,
        });
      }
    }, 1000);
  };
  // 点击发送短信验证码
  sendMsg = () => {
    // 01: 保证手机号和图形验证码符合校验规则
    // console.log(this.ref1)
    this.ref1.current
      .validateFields(["mobile", "captcha"])
      .then((res) => {
        // console.log(res);
        //02: 表示手机号和图形验证码负责校验规则,接下来保证输入的图形验证码是正确的
        axios
          .post(url.captchaverify, {
            key: this.state.key,
            captcha: res.captcha,
          })
          .then((res1) => {
            console.log(res1);
            if (res1.data.errNo == 0) {
              // 说明图形验证码输入正确,接下里调用发送短信接口,发送短信
              axios
                .post(url.sendmsg, {
                  token: res1.data.context.token,
                  mobile: res.mobile,
                  type: 0,
                })
                .then((res2) => {
                  console.log(res2);
                  if (res2.data.errNo == 0) {
                    // 短信发送成功
                    message.success("短信发送成功", 1);
                    // 开启倒计时 (从30到0 倒计时)
                    this.timeover();
                    // 设置登录按钮可以点击
                    this.setState({
                      disabledClick: false,
                    });
                    // 设置requestId
                    this.setState({
                      requestId: res2.data.requestId,
                    });
                  } else {
                    // 短信发送失败
                    message.error(res2.data.errText, 1);
                    // 重新生成新的图形验证码
                    this.ref2.current.loadImg();
                    // 清空手机号和图形验证码的输入内容
                    this.ref1.current.setFieldsValue({
                      mobile: "",
                      captcha: "",
                    });
                  }
                });
            } else {
              // 说明图像验证码输入错误
              message.error(res1.data.errText, 1);
              // 重新生成新的图形验证码
              this.ref2.current.loadImg();
              //清空图形验证码输入项
              this.ref1.current.setFieldsValue({
                captcha: "",
              });
            }
          })
          .catch((e) => {});
      })
      .catch((e) => {
        console.log(e);
      });
  };
}

export default withRouter(MobileLogin);
